package cn.truistic.enmicromsg.common.util;

import android.accessibilityservice.AccessibilityService;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.List;

import cn.truistic.enmicromsg.app.EnApplication;
import cn.truistic.enmicromsg.base.WeChatAutomationService;
import cn.truistic.enmicromsg.base.WeChatLogService;

/**
 * Created by admin on 2018/6/19.
 * name ： ts
 * 用图：微信辅助类
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public abstract class WxHeple {
    protected static EnApplication mEnApplication ;
    public AccessibilityNodeInfo node = null;
    protected AccessibilityService mAccessibilityService;


    public abstract void isAutomationNearby(AccessibilityEvent event, int eventType );


    public WxHeple(EnApplication mContext,AccessibilityService mAccessibilityService) {
        this.mEnApplication = mContext;
        this.mAccessibilityService = mAccessibilityService;
    }

    /**
     * 跳转微信主界面
     */
    public static void intentWechat(Context mEnApplication) {
        Intent wxIntent = new Intent();
        ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
        wxIntent.setAction(Intent.ACTION_MAIN);
        wxIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        wxIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        wxIntent.setComponent(cmp);
        mEnApplication.startActivity(wxIntent);
    }


    /**
     * "am force-stop com.tencent.mm"
     * 模拟物理点击方法
     * @param cmd
     */
    public static void execShellCmd(String cmd) {
        try {
            // 申请获取root权限，这一步很重要，不然会没有作用
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }


    /**
     * 判断AccessibilityService服务是否已经启动
     * @return
     */
    // To check if service is enabled
    public static boolean isAccessibilitySettingsOn(Context mEnApplication) {
        int accessibilityEnabled = 0;
        // TestService为对应的服务
        String service = mEnApplication.getPackageName() + "/" + WeChatAutomationService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(mEnApplication.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(mEnApplication.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**
     * 复制方法
     * @param string
     */
    public void copyToBoard(String string) {
        ClipboardManager cm = (ClipboardManager) mEnApplication.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("text", string);
        cm.setPrimaryClip(clipData);
    }

    //睡眠时间 ，如果操作过快微信可能会封号！
    public void sleepTime(long miss){
        try {
            Thread.sleep(miss);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否找到某个文本
     * @param text
     * @return
     */
    public boolean isFindText(String text) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText(text);
            if (list.size() > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否找到某个ID
     * @param id
     * @return
     */
    public boolean isFindId( String id ) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
            if ( list.size() > 0 ) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否找到某个ID
     *
     * @param id
     * @return
     */
    public boolean isFindId(String id, int i) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
            if (list.size() > 0) {
                node = list.get(i);
            }
        }
        targetNode = node;
        if ( targetNode != null ) {
            return true;
        }
        return false;
    }

    /*****
     * 根据id和text一起判断点击
     */
    public void WXfindIdTextAndClick(String id, String text, int i) {
        // 查找当前窗口中id为“id”的按钮
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        AccessibilityNodeInfo targetNode1 = null;
        node = null;
        if (targetNode == null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
            if (list.size() > 0) {
                targetNode = list.get(i);
                Log.i("890", targetNode + "node");
                if (targetNode.getText().equals(text)) {
                    node = targetNode;
                }
            }
        }
        targetNode1 = node;

        if (targetNode1 != null) {
            final AccessibilityNodeInfo n = targetNode1;
            performClick(n);
            Log.e("TAG", n + "node");
        }
    }

    /**
     * 执行具体的点击
     *
     * @param nodeInfo
     */
    public void performClick(AccessibilityNodeInfo nodeInfo) {
        if (nodeInfo == null) {
            return;
        }
        if (nodeInfo.isClickable()) {
            nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        } else {
            performClick(nodeInfo.getParent());
        }
    }

    /**
     * 模拟点击文字按钮事件
     *
     * @param text
     * @param i
     */
    @SuppressLint("NewApi")
    public void findTextAndClick(String text, int i ) {
        // 查找当前窗口中包含“xx”文字的按钮
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByText(text);
            if (list.size() > 0) {
                node = list.get(i);
            }
        }
        targetNode = node;
        if (targetNode != null) {
            final AccessibilityNodeInfo n = targetNode;
            performClick(n);
        }
    }

    /**
     * 模拟点击id事件
     * @param id
     * @param i
     */
    public void findIdAndClick(String id, int i) {
        // 查找当前窗口中id为“id”的按钮
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;

        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo
                    .findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
            if (list.size() > 0) {
                node = list.get(i);
            }
        }
        targetNode = node;

        if (targetNode != null) {
            final AccessibilityNodeInfo n = targetNode;
            performClick(n);
        }
    }

    public void findContentAndClick(String id, int i, String text, int child) {
        // 查找当前窗口中包含“xx”文字的按钮
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
            if (list.size() > 0) {
                node = list.get(i);
            }
        }
        targetNode = node;
        if (targetNode != null) {
            final AccessibilityNodeInfo n = targetNode.getChild(child);
            Log.i("123", n + "");
            if (n.getContentDescription().toString().equals(text)) {
                performClick(n);
            }
        }
    }

    public boolean isFindWXBouns(String id, int i) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
        AccessibilityNodeInfo targetNode = null;
        Log.i("zzz1", list.size() + "aaaa"+i);
        if (list.size() > 0) {
            Rect nodeRect = new Rect();
            AccessibilityNodeInfo accessibilityNodeInfo=list.get(i);
            Log.i("zzz1", list.size() + "bb"+accessibilityNodeInfo);
            accessibilityNodeInfo.getBoundsInScreen(nodeRect);
            Log.i("zzz1", nodeRect.bottom + "" + nodeRect.top);
            if (nodeRect.bottom ==1263  && nodeRect.top == 1167) {
                return true;
            }

        }
        return false;
    }

    /**
     * 粘贴
     * @param id
     * @param i
     */
    public void paste(String id, int i) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        try {
            if (node == null) {
                List<AccessibilityNodeInfo> list = nodeInfo
                        .findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
                if (list.size() > 0)
                    node = list.get(i);
            }
            targetNode = node;
            if (targetNode != null) {
                targetNode.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                targetNode.performAction(AccessibilityNodeInfo.ACTION_PASTE);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 判断是否找到某个ID得到list数量
     * @param id
     * @return
     */
    public int isFindIdlistnum(String id) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo targetNode = null;
        node = null;
        if (node == null) {
            List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/" + id);
            if (list.size() > 0) {
                return list.size();
            }
        }
        return 0;
    }

    //自动输入打招呼内容
    public void inputHello(String hello) {
        AccessibilityNodeInfo nodeInfo = mAccessibilityService.getRootInActiveWindow();
        //找到当前获取焦点的view
        AccessibilityNodeInfo target = nodeInfo.findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
        if (target == null) {
            Log.d("TAG", "inputHello: null");
            return;
        }
        ClipboardManager clipboard = (ClipboardManager) mEnApplication.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", hello);
        clipboard.setPrimaryClip(clip);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            target.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
    }
}
